﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Lyon.Utility
{
    /// <summary>
    /// 对象工具
    /// </summary>
    static public class ObjectTool
    {
        /// <summary>
        /// 将对象转化成Xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        static public string ToXml<T>(T obj)
        {
            Guard.ArgumentNotNull(obj, "obj");
            using (StringWriter writer = new StringWriter())
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }
        /// <summary>
        /// 将Xml字符串转化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        static public T FromXml<T>(string xmlString)
        {
            Guard.ArgumentNotNullOrEmptyString(xmlString, "xmlString");
            using (StringReader reader = new StringReader(xmlString))
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(reader);
            }
        }
    }
}
